const { Service } = require("egg");
const crypto = require("crypto");//加密/生成随机串
class AdminService extends Service {
  // 商家注册
  async adminRegiter(username, password) {
    const db = this.ctx.model.Admininfo;
    const res = await db.findOne({ username });
    if (res) {
      return {
        code: 409, //客户端请求的更改与资源当前状态冲突
        success: false,
        error: "账号已存在",
      };
    } else {
      // 创建hash对象
      const hash = crypto.createHash("sha256").update(password);
      // 生成hash值
      const passwordHash = hash.digest("hex");
      await db.create({ username, password: passwordHash });
      return {
        code: 201, // 创建了新资源
        msg: "成功",
      };
    }
  }
  //   商家登录
  async adminLogin(username, password) {
    const db = this.ctx.model.Admininfo;
    // 创建hash对象
    const hash = crypto.createHash("sha256").update(password);
    // 生成hash值
    const passwordHash = hash.digest("hex");
    const res = await db
      .findOne(
        { username, password: passwordHash },
        { cooperation: false, createdAt: false, updatedAt: false }
      )
      .lean(); //lean：返回普通对象
    if (res) {
      const token = this.ctx.generateToken(res._id.toString());
      console.log("tokenvvv", token);
      return {
        data: { ...res, token },
        msg: "成功",
      };
    } else {
      return {
        error: "账号或密码错误",
        success: false,
        code: 422, //422表示服务端理解客户端请求，但无法处理，通常表示数据格式错误或缺少字段
      };
    }
  }
  //   商家信息修改
  async adminUpdate(info) {
    const db = this.ctx.model.Admininfo;
    const res = await db.updateOne(info);
    if (res) {
      return {
        msg: "修改成功",
      };
    } else {
      return {
        error: "修改失败",
        success: false,
        code: 422, //422表示服务端理解客户端请求，但无法处理，通常表示数据格式错误或缺少字段
      };
    }
  }
  //   计算用户到商家的距离
  async distanceCalculator(_id, from) {
    const { ctx, app } = this;
    const { cooperation } = await ctx.model.Admininfo.findById(_id)
      .select("cooperation")
      .lean();
    const url = "https://apis.map.qq.com/ws/distance/v1/matrix?";

    const params = {
      key: app.config.map.key,
      from: JSON.parse(from).join(","),
      to: cooperation.join(","),
      mode: "bicycling",
    };
    const queryString = Object.keys(params)
      .map((key) => `${key}=${params[key]}`)
      .join("&");
    const json = await fetch(url + queryString);
    const data = await json.json();
    if (!data.status) {
      let distance = data.result.rows[0].elements[0].distance;
      if (distance >= 1000) {
        distance = (distance / 1000).toFixed(1) + "km";
      } else {
        distance = distance + "m";
      }
      console.log(distance);
      return {
        msg: "成功",
        data: { distance },
      };
    } else {
      return {
        error: data.result,
        success: false,
        code: 500,
      };
    }
  }
  // 计算电动车用户到商家的耗时与距离
  async durationCaulcator(_id, from) {
    const { ctx, app } = this;
    const { cooperation } = await ctx.model.Admininfo.findById(_id)
      .select("cooperation")
      .lean();
    const url = "https://apis.map.qq.com/ws/direction/v1/ebicycling/?";

    const params = {
      key: app.config.map.key,
      from: JSON.parse(from).join(","),
      to: cooperation.join(","),
    };
    const queryString = Object.keys(params)
      .map((key) => `${key}=${params[key]}`)
      .join("&");
    console.log(url + queryString);
    const json = await fetch(url + queryString);
    const data = await json.json();
    if (!data.status) {
      let { duration, distance } = data.result.routes[0];
      if (distance >= 1000) {
        distance = (distance / 1000).toFixed(1) + "km";
      } else {
        distance = distance + "m";
      }
      console.log(data.result.routes[0]);
      return {
        msg: "成功",
        data: { duration, distance },
      };
    } else {
      return {
        error: data.result,
        success: false,
        code: 500,
      };
    }
  }
}

module.exports = AdminService;
